﻿using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Wpf.Ui;

namespace DesignPattern.Controls
{
    //NavigationPresenter是一个框架级的控件，需要全局样式和资源
    //需要在App.xaml中引入，仅仅引入命名空间是不够的
    public class NavigationPresenter : Control
    {
        //默认代码，WPF控件模板机制的关键部分，OverrideMetadata用于重写依赖属性的元数据。告诉WPF使用默认样式
        //静态构造函数在类第一次被使访问时执行，而且只会执行一次，用于初始化类的静态成员或执行一些只需要执行一次的初始化操作
        //DefaultStyleKeyProperty用于指定控件的默认样式（DefaultStyle）的键值，这个键值用于在资源字典中查找控件的样式定义
        static NavigationPresenter()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationPresenter),
                new FrameworkPropertyMetadata(typeof(NavigationPresenter)));
        }
        public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register(
            nameof(ItemsSource),
            typeof(object),
            typeof(NavigationPresenter),
            new PropertyMetadata(null)
        );
        //定义依赖属性
        public static readonly DependencyProperty TemplateButtonCommandProperty = DependencyProperty.Register(
            nameof(TemplateButtonCommand),
            typeof(Wpf.Ui.Input.IRelayCommand),
            typeof(NavigationPresenter),
            new PropertyMetadata(null)
        );
        public object? ItemsSource
        {
            get => GetValue(ItemsSourceProperty);
            set => SetValue(ItemsSourceProperty, value);
        }
        //在点击标题栏按钮后获取触发的命令
        public Wpf.Ui.Input.IRelayCommand TemplateButtonCommand =>
            (Wpf.Ui.Input.IRelayCommand)GetValue(TemplateButtonCommandProperty);
        //创建该类的新实例并设置默认的Command
        //构造函数只在控件创建时执行一次，因此SetValue没有放到TemplateButtonCommand的Set里面
        public NavigationPresenter()
        {
            SetValue(TemplateButtonCommandProperty,
                new Wpf.Ui.Input.RelayCommand<string>(pageTage => OnTemplateButtonClick(pageTage)));
        }
        private void OnTemplateButtonClick(string? pageTage)
        {
            INavigationService navigationService = App.Services.GetRequiredService<INavigationService>();
            if (pageTage is not null)
            {
                _ = navigationService.Navigate(pageTage);
            }
        }
    }
}